import { getLocalJson, setLocalJson } from "./storage.ts";
import { PropChanged } from "./prop-changed.ts";

/**
 * 本地缓存对象
 */
export abstract class LocalCacheObject<TSelf extends LocalCacheObject<any, any>, TValues> extends PropChanged<TSelf, TValues> {
  protected constructor(private readonly _cacheKey: string) {
    super();
  }

  protected loadCache() {
    const local = getLocalJson<TValues>(this._cacheKey);
    if (local) {
      this.assignFromLocal?.(local);
    }
  }

  protected _save() {
    setLocalJson(this._cacheKey, this.toJson());
  }

  protected afterSetProp() {
    this._save();
  }

  protected abstract assignFromLocal(local: TValues): void;

  abstract toJson(): TValues;

  removeLocal() {
    localStorage.removeItem(this._cacheKey);
  }
}
